package cn.rwklyd.BookKeeping.controller;

import cn.rwklyd.BookKeeping.constant.MessageConstant;
import cn.rwklyd.BookKeeping.mapper.mybatisPlus.AdminMapper_Mp;
import cn.rwklyd.BookKeeping.service.AdminService;
import cn.rwklyd.BookKeeping.pojo.Result;
import cn.rwklyd.BookKeeping.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin")
@Slf4j
@Tag(name = "管理员管理", description = "管理员管理相关接口")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private AdminMapper_Mp adminMapper_mp;

    @GetMapping("/getAllAdmins")
    @PreAuthorize("hasAuthority('view_users')")
    @Operation(summary = "获取全部用户信息", description = "获取全部用户信息")
    public Result<PageInfo<User>> getAllAdmins(@RequestParam Integer page,
                               @RequestParam Integer pageSize,
                               @RequestParam String parameter) {
        PageHelper.startPage(page, pageSize);
//        List<User> manufacturers = adminService.getAllAdmins(parameter);      // 使用传统的xml方式
        List<User> manufacturers = adminMapper_mp.selectList(null); // 使用mybatisplus 的方式实现查询
        PageInfo<User> pageInfo = new PageInfo<>(manufacturers);
        return Result.success(pageInfo);
    }

    @PostMapping("/addAdmin")
    @PreAuthorize("hasAuthority('add_users')")
    @Operation(summary = "添加用户", description = "添加用户")
    public Result<String> addAdmin(@RequestBody User user) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        if (adminMapper_mp.selectCount(queryWrapper) > 0) {
            return Result.error(MessageConstant.USERNAME_ALREADY_EXISTS);
        }

        // 检查邮箱是否已存在
        LambdaQueryWrapper<User> emailWrapper = new LambdaQueryWrapper<>();
        emailWrapper.eq(User::getEmail, user.getEmail());
        if (adminMapper_mp.selectCount(emailWrapper) > 0) {
            return Result.error(MessageConstant.EMAIL_ALREADY_EXISTS);
        }

        // 对密码进行加密处理
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);

        adminMapper_mp.insert(user);
        return Result.success(MessageConstant.SUCCESS);
    }

    /*@PutMapping("/updateAdmin")
    @PreAuthorize("hasAuthority('edit_users')")
    @Operation(summary = "更新用户", description = "更新用户")
    public Result<String> updateAdmin(@RequestBody User user) {
        adminMapper_mp.updateById(user);
        return Result.success("更新成功");
    }*/

    @PutMapping("/updateAdmin")
    @PreAuthorize("hasAuthority('edit_users')")
    @Operation(summary = "更新用户", description = "更新用户")
    public Result<String> updateAdmin(@RequestBody User user) {
        // 先检查邮箱是否已被其他用户使用
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, user.getEmail())
                .ne(User::getId, user.getId()); // 排除当前用户

        // 查询是否存在相同邮箱的其他用户
        Long count = adminMapper_mp.selectCount(queryWrapper);

        if (count > 0) {
            // 存在相同邮箱的其他用户，返回错误信息
            return Result.error(MessageConstant.EMAIL_ALREADY_EXISTS);
        }

        // 邮箱验证通过，执行更新操作
        adminMapper_mp.updateById(user);
        return Result.success(MessageConstant.SUCCESS);
    }

    @DeleteMapping("/deleteAdmin")
    @PreAuthorize("hasAuthority('delete_users')")
    @Operation(summary = "删除用户", description = "删除用户")
    public Result<String> deleteAdmin(@RequestParam Integer id) {
        adminMapper_mp.deleteById(id);
        return Result.success(MessageConstant.SUCCESS);
    }

}
